package com.example.pda.view;

import android.content.Context;
import android.graphics.Rect;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class FormLayoutManger extends LinearLayoutManager {
    // 同步滑动时间
    private final List<RecyclerView> mRecyclerViews = new ArrayList<>();
    // 垂直滑动边界判断
    private int mSumDy = 0;
    private int mTotalHeight = 0;
    // 横向滑动边界判断
    private int mSumDx = 0;
    private int mTotalWidth = 0;

    private boolean canHorizontallyScroll = true;
    private boolean canVerticallyScroll = true;

    public FormLayoutManger(Context context, RecyclerView... recyclerViews) {
        super(context);
        if (recyclerViews != null) {
            for (RecyclerView recyclerView : recyclerViews) {
                connectRecyclerView(recyclerView);
            }
        }
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
    }


    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (getItemCount() <= 0 || state.isPreLayout()) {
            return;
        }
        detachAndScrapAttachedViews(recycler);
        View first = recycler.getViewForPosition(0);
        measureChildWithMargins(first, 0, 0);
        int width = getDecoratedMeasuredWidth(first);
        int height = getDecoratedMeasuredHeight(first);
        if (mItemFrames == null || mItemFrames.size() != getItemCount()) {
            mItemFrames = new ArrayList<>();
            for (int i = 0; i < getItemCount(); i++) {
                View scrap = recycler.getViewForPosition(i);
                addView(scrap);
                Rect rect = new Rect();
                rect.set(0, i * height, width, (i + 1) * height);
                mItemFrames.add(rect);
            }
        }
        mTotalWidth = Math.max(width, getHorizontallySpace());
        mTotalHeight = Math.max(getItemCount() * height, getVerticalSpace());
        fill(recycler, state);
    }

    private List<Rect> mItemFrames = new ArrayList<>();

    private void fill(RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (getItemCount() <= 0 || state.isPreLayout()) {
            return;
        }
        detachAndScrapAttachedViews(recycler);
        Rect displayRect = new Rect(mSumDx, mSumDy, getHorizontallySpace() + mSumDx, getVerticalSpace() + mSumDy);
        for (int i = 0; i < getItemCount(); i++) {
            Rect frame = mItemFrames.get(i);
            if (Rect.intersects(displayRect, frame)) {
                View scrap = recycler.getViewForPosition(i);
                addView(scrap);
                measureChildWithMargins(scrap, 0, 0);
                layoutDecorated(scrap, frame.left - mSumDx, frame.top - mSumDy, frame.right - mSumDx, frame.bottom - mSumDy);
            }
        }
    }

    @Override
    public boolean canScrollHorizontally() {
        return canHorizontallyScroll;
    }

    @Override
    public boolean canScrollVertically() {
        return canVerticallyScroll;
    }

    public void setCanHorizontallyScroll(boolean canHorizontallyScroll) {
        this.canHorizontallyScroll = canHorizontallyScroll;
    }

    public void setCanVerticallyScroll(boolean canVerticallyScroll) {
        this.canVerticallyScroll = canVerticallyScroll;
    }

    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        int travel = dx;
        //如果滑动到最顶部
        if (mSumDx + dx < 0) {
            travel = -mSumDx;
        } else if (mSumDx + dx > mTotalWidth - getHorizontallySpace()) {
            //如果滑动到最底部
            travel = mTotalWidth - getHorizontallySpace() - mSumDx;
        }

        mSumDx += travel;
        // 平移容器内的item
        offsetChildrenHorizontal(-travel);
        fill(recycler, state);
        return dx;
    }

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        int travel = dy;
        //如果滑动到最顶部
        if (mSumDy + dy < 0) {
            travel = -mSumDy;
        } else if (mSumDy + dy > mTotalHeight - getVerticalSpace()) {
            //如果滑动到最底部
            travel = mTotalHeight - getVerticalSpace() - mSumDy;
        }

        mSumDy += travel;
        // 平移容器内的item
        offsetChildrenVertical(-travel);
        fill(recycler, state);
        return dy;
    }

    private int getVerticalSpace() {
        return getHeight() - getPaddingBottom() - getPaddingTop();
    }

    private int getHorizontallySpace() {
        return getWidth() - getPaddingEnd() - getPaddingStart();
    }


    public void connectRecyclerView(RecyclerView recyclerView) {
        recyclerView.addOnScrollListener(mScrollListener);
        mRecyclerViews.add(recyclerView);
    }

    private final RecyclerView.OnScrollListener mScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            // 以下场景处理的是，滑动过程中手指松开，移到另外一个recyclerview进行滚动
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                // 该recyclerview进入滚动状态的时候，其余四个要先停止滚动
                int currentIndex = mRecyclerViews.indexOf(recyclerView);
                for (int i = 0; i < mRecyclerViews.size(); i++) {
                    if (i != currentIndex) {
                        mRecyclerViews.get(i).stopScroll();
                    }
                }
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
                // 手指所放在的当前recyclerview的下标
                int currentIndex = mRecyclerViews.indexOf(recyclerView);
                for (int i = 0; i < mRecyclerViews.size(); i++) {
                    if (i != currentIndex) {
                        mRecyclerViews.get(i).scrollBy(dx, dy);
                    }
                }
            }
        }
    };
}
